package com.ruoyi.exception;

import com.ruoyi.result.JSONResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult exceptionHandler(Exception e){
        e.printStackTrace();
        return JSONResult.error(e.getMessage(),"100");
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult globalCustomHandler(GlobalCustomException e){
        e.printStackTrace();
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult methodArgumentNotValidHandler(MethodArgumentNotValidException e){
        //e.getBindingResult().getAllErrors().get(0).getDefaultMessage()
        StringBuilder str = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(error -> {
            str.append(error.getDefaultMessage()).append("-");
        });
        e.printStackTrace();
        return JSONResult.error(str.toString(),GlobalErrorCodeEnum.JSR303.getCode());
    }
}
